package pers.vic.upload.socket.config;

import cn.xuqiudong.common.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import pers.vic.upload.constant.SessionAttr;
import pers.vic.upload.login.model.User;
import pers.vic.upload.login.service.LoginService;

import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map;

/**
 * 描述:
 * @author Vic.xu
 * @date 2022-07-29 11:15
 */
public class MineHttpSessionHandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    private final Logger logger = LoggerFactory.getLogger(MineHttpSessionHandshakeInterceptor.class);


    public boolean needLogin;

    public LoginService loginService;




    public void setNeedLogin(boolean needLogin) {
        this.needLogin = needLogin;
    }

    public void setLoginService(LoginService loginService) {
        this.loginService = loginService;
    }

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        if (!needLogin) {
            return true;
        }
        User user = getUser(request);
        if (user == null) {
            return  false;
        }
        attributes.put(SessionAttr.SESSION_USER, user);
        attributes.put(SessionAttr.USER_ID, user.getId());
        attributes.put(SessionAttr.USER_NAME, user.getUsername());
        //attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
        return true;
    }

    /**
     * 原本是通过session获取用户信息的， 但是由于前端说无法设置请求header，所以无法获取session;
     * 因此改为从redis中获取
     * HttpSession session = getSession(request);
     * User user = (User) session.getAttribute(SessionAttr.SESSION_USER);
     * @param request ServerHttpRequest
     * @return User
     */
    private User getUser(ServerHttpRequest request){
         HttpSession session = getSession(request);
        if (session != null) {
            return  (User) session.getAttribute(SessionAttr.SESSION_USER);
        }
        String sid = getRequestParameter(request, "sid");
        if (sid == null) {
            return null;
        }
        return loginService.getCacheUser(sid);
    }

    private HttpSession getSession(ServerHttpRequest request) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            Map<String, String[]> parameterMap = serverRequest.getServletRequest().getParameterMap();
            logger.info("parameterMap = {}", JsonUtil.toJson(parameterMap));

            return serverRequest.getServletRequest().getSession(isCreateSession());
        }
        return null;
    }

    /**
     * 获取请求中的参数
     * @param request ServerHttpRequest
     * @return parameter
     */
    private String getRequestParameter(ServerHttpRequest request, String name) {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest serverRequest = (ServletServerHttpRequest) request;
            Map<String, String[]> parameterMap = serverRequest.getServletRequest().getParameterMap();
            logger.info("parameterMap = {}", JsonUtil.toJson(parameterMap));

            return serverRequest.getServletRequest().getParameter(name);
        }
        return null;
    }



    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        logger.info("afterHandshake");
    }
}
